<?php
global $ofj_api_url;
global $wpdb;

if(isset($_POST['fetch_jobs_btn'])) {
    // Fetch jobs Button pressed.
    print_r ('<pre>');
    $result = json_decode(file_get_contents('http://lehoaian.info/lhablog/wp-content/plugins/odesk-project-history/~017b947e6bb09dadc5.json'));
	
	// print_r($result);
    $jobs_list = $result->profile->assignments->assignment;
    
    /*
    $post = array(
        'ID'             => [ <post id> ] //Are you updating an existing post?
        'post_author'    => [ <user ID> ] //The user ID number of the author.
        'post_category'  => [ array(<category id>, <...>) ] //post_category no longer exists, try wp_set_post_terms() for setting a post's categories
        'post_content'   => [ <the text of the post> ] //The full text of the post.
        'post_date'      => [ Y-m-d H:i:s ] //The time post was made.
        'post_date_gmt'  => [ Y-m-d H:i:s ] //The time post was made, in GMT.
        'post_excerpt'   => [ <an excerpt> ] //For all your post excerpt needs.
        'post_name'      => [ <the name> ] // The name (slug) for your post
        'post_status'    => [ 'draft' | 'publish' | 'pending'| 'future' | 'private' | custom registered status ] //Set the status of the new post.
        'post_title'     => [ <the title> ] //The title of your post.
        'tags_input'     => [ '<tag>, <tag>, <...>' ] //For tags.
        'tax_input'      => [ array( 'taxonomy_name' => array( 'term', 'term2', 'term3' ) ) ] // support for custom taxonomies. 
    );
    */
    
    $query = "  SELECT LEFT(CONCAT( '~', post_name ), 19), term.term_id
                    FROM $wpdb->posts AS post
                    LEFT JOIN $wpdb->postmeta AS meta ON post.ID = meta.post_id 
                    LEFT JOIN $wpdb->term_relationships AS term_rel ON post.ID = term_rel.object_id 
                    LEFT JOIN $wpdb->term_taxonomy AS term_ta ON term_rel.term_taxonomy_id = term_ta.term_taxonomy_id
                    LEFT JOIN $wpdb->terms AS term ON term.term_id = term_ta.term_taxonomy_id
                WHERE term_ta.taxonomy = 'category' AND term.slug = 'odesk_jobs'
                    AND (post.post_status = 'publish')
                GROUP BY post_name";

                $row = $wpdb->get_col($query, 0);
    
    $query = "  SELECT term_id FROM $wpdb->terms WHERE slug = 'odesk_jobs' LIMIT 1";
    $category_id = $wpdb->get_var($query, 0, 0);
    if(!$category_id) $category_id = 1; // If not set, set to default cate
    print_r($category_id);
    
    if(is_array($jobs_list)) {
        foreach($jobs_list as $job) {
            // print_r($job);
            // 10/08/2012
            // echo date_create_from_format('m/d/Y', $job->as_to_full);
            if(in_array($job->as_ciphertext_opening_recno, $row)) {
                echo "Post $job->as_ciphertext_opening_recno duplicated <br>";
            } else {
                echo "========================================== <br>";
                echo "Processing post $job->as_ciphertext_opening_recno <br>";
                // $post_date = date_create_from_format('m/d/Y', $job->as_to_full);
                // $post_date = DateTime::createFromFormat('m/d/Y', $job->as_to_full);
                $post = array(
                     'post_category'  => array( $category_id )
                    ,'post_content'   => $job->feedback->comment
                    ,'post_date'      => date('Y-m-d',strtotime($job->as_to_full))
                    ,'post_excerpt'   => $job->as_description
                    ,'post_name'      => $job->as_ciphertext_opening_recno
                    ,'post_status'    => 'publish'
                    ,'post_title'     => $job->as_opening_title
                    ,'tax_input'      => array( 
                        'post_format' => 'post-format-quote'
                    )
                );
                
                print_r($post);
                
                $wp_error;
                $pid;
                if( !($pid = wp_insert_post( $post , $wp_error )) ) {
                    print_r($wp_error );
                    echo 'Processing post failed <br>';
                } else {
                    // Try to input custom fields.
                    echo 'Trying to add post meta data';
                    add_post_meta($pid, 'odesk-job-score', $job->feedback->score, true);
                    add_post_meta($pid, 'odesk-job-scores', $job->feedback->scores, true);
                    add_post_meta($pid, 'odesk-job-permalink', (isset($job->permalink))?$job->permalink:'private', true);
                    add_post_meta($pid, 'odesk-job-from', $job->as_from_full, true);
                    add_post_meta($pid, 'odesk-job-to', $job->as_to_full, true);
                }
            }
        }
    }
        
    
    print_r ('</pre>');
} else {
?>
<div class="wrap">
    <h2>Get jobs from oDesk History</h2>
    <form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
        <ul>
        	<li>
                <label for="odesk_profile_uid">Your profile UID : </label>
                <input type="text" name="odesk_profile_uid" />
            </li>
        	<li><input type="submit" value="Fetch Jobs" class="button-primary" name="fetch_jobs_btn" /></li>
        </ul>
    </form>
</div>

<?php
}
?>